package com.example.dell.newstart.login;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.dell.newstart.MainActivity;
import com.example.dell.newstart.R;
import com.example.dell.newstart.base.BaseActivity;
import com.example.dell.newstart.base.RequestInterface;
import com.example.dell.newstart.base.ServerResponse;
import com.example.dell.newstart.bean.MyApp;
import com.example.dell.newstart.bean.User;
import com.example.dell.newstart.res.LogActivity;
import com.example.dell.newstart.utils.SharedPreferenceUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Login extends BaseActivity {

    private String username;
    private  String pwd;

    @BindView(R.id.user_name)
    EditText edittext1;
    @BindView(R.id.pwd)
    EditText edittext2;
    @BindView(R.id.login_ig)
    ImageView loginIg;
    @BindView(R.id.cheack_btn1)
    CheckBox checkbox1 ;
    @BindView(R.id.cheak_btn2)
    CheckBox checkbox2;

    @Override
    public int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);

    }

    @Override
    public void initData() {
        Glide.with(this).load(R.mipmap.unlogin1)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(loginIg);
        String accountStr = (String) SharedPreferenceUtil.get(this, "account", ""/*这儿不能放null，因为辅助类中取值的时候会根据这的值的类型取对应类型的值，之前问题就出在这里*/);
        String passwordStr = (String) SharedPreferenceUtil.get(this, "password", "");
        boolean loginInfo = (boolean) SharedPreferenceUtil.get(this, "loginInfo", false);
        boolean autoLogin = (boolean) SharedPreferenceUtil.get(this, "autoLogin", false);
        checkbox1.setChecked(loginInfo);//记住密码
        checkbox2.setChecked(autoLogin);//自动登入
        if (loginInfo) {
            edittext1.setText(accountStr);
            edittext2.setText(passwordStr);
        }
        //验证文本框输入的合法性
        if (autoLogin) {
            if (TextUtils.isEmpty(accountStr)) {
                toastShort("账号不能为空！");
                return;
            }
            if (TextUtils.isEmpty(passwordStr)) {
                toastShort("密码不能为空！");
                return;
            }
           login();
        }
    }


    @OnClick({R.id.new_user, R.id.forget_pwd, R.id.login_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                beginLogin();
               // toastShort("登陆");
                break;
            case R.id.new_user:
                //toastShort("注册");
               // toastShort("页卡演");
                goNextActivity(LogActivity.class);
                break;
            case R.id.forget_pwd:
               // toastShort("忘记密码(注册)");
                goNextActivity(LogActivity.class);
                break;


        }
    }

//    private  void ifcheck1()
//    {
//        if (checkbox1.isChecked()) {
//            SharedPreferenceUtil.put(this, "loginInfo", true);
//
//        } else {
//            SharedPreferenceUtil.put(this, "loginInfo", false);
//        }
//    }
//    private  void ifcheck2(){
//        if(checkbox1.isChecked())
//        {
//            if (checkbox2.isChecked()) {
//                SharedPreferenceUtil.put(this, "autoLogin", true);
//            } else {
//                SharedPreferenceUtil.put(this, "autoLogin", false);
//            }
//        }
//        else
//            toastShort("账户密码不能为空，请先记住密码");
//    }


    private void beginLogin() {
        String accountString = edittext1.getText().toString().trim();
        String passwordString = edittext2.getText().toString().trim();
        // TODO: 2018/12/25 验证账号密码合法性
        if (TextUtils.isEmpty(accountString)) {
            toastShort("账号不能为空！");
            return;
        }
        if (TextUtils.isEmpty(passwordString)) {
            toastShort("密码不能为空！");
            return;
        }
        if (checkbox1.isChecked()) {
            //把账号、密码存到sharedPreference
            SharedPreferenceUtil.put(this, "account", accountString);
            SharedPreferenceUtil.put(this, "password", passwordString);
            SharedPreferenceUtil.put(this, "loginInfo", true);

            if (checkbox2.isChecked()) {
                SharedPreferenceUtil.put(this, "autoLogin", true);
            } else {
                SharedPreferenceUtil.put(this, "autoLogin", false);
            }
        } else {
            SharedPreferenceUtil.put(this, "account", "");
            SharedPreferenceUtil.put(this, "password", "");
            SharedPreferenceUtil.put(this, "loginInfo", false);
        }
        login();
    }

    public void login() {

        username = edittext1.getText().toString();
        pwd = edittext2.getText().toString();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.Login3 requestInterfaceLogin = retrofit.create(RequestInterface.Login3.class);
        Call<ServerResponse<User>> call = requestInterfaceLogin.login(username, pwd);

        call.enqueue(new Callback<ServerResponse<User>>() {

            @Override
            public void onResponse(Call<ServerResponse<User>> call, Response<ServerResponse<User>> response) {
                /**
                 * response.body()获取到返回的ServerResponse，再通过获取Status判断是否
                 * 登陆成功/请求数据成功
                 */
                if (response.body() == null) {
                    toastShort("网络异常，请检查网络配置");
                    return;
                }
                //log(response.body().getMsg());
                if (response.body().getStatus() == 0) {
                    //获取返回的数据（就是泛型ServerResponse中的T所代表的数据）
                    User user = response.body().getData();
                    toastShort("连接成功！");
                    //获取当前应用
                    MyApp app = (MyApp) getApplication();
                    //把返回的user保存到myAPP中
                    app.setCurrentUser(user);
                    //Log.d(TAG, "用户onResponse: user^^^^^^^^^^" + user.toString());

                    if(user==null)
                        Toast.makeText(Login.this, "登陆失败", Toast.LENGTH_SHORT).show();
                    else
                        //跳转主活动

                    {
                        Toast.makeText(Login.this, "登陆成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(Login.this,MainActivity.class);
                        startActivity(intent);}

                           finish();
                }
                else
                    Toast.makeText(Login.this, "登陆失败,密码输入错误！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<ServerResponse<User>> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
                toastShort("连接失败！");
            }
        });
    }
 /*//获取原始数据，对应第一个button
    public void (View view) {
        edittext1 = findViewById(R.id.user_name);//获取文本框数据wo
       edittext2 = findViewById(R.id.pwd);
       username = edittext1.getText().toString();
       pwd = edittext2.getText().toString();

        //Log.d(TAG, "login: 账号："+accountString+" 密码 "+passwordString);
        //Toast.makeText(LoginActivity.this, "账号是：" + accountString + " 密码是：" + passwordString, Toast.LENGTH_SHORT).show();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.Login3 requestInterfaceLogin = retrofit.create(RequestInterface.Login3.class);
        Call<ServerResponse<User>> call = requestInterfaceLogin.login(username, pwd);

        call.enqueue(new Callback<ServerResponse<User>>() {

            @Override
            public void onResponse(Call<ServerResponse<User>> call, Response<ServerResponse<User>> response) {
                try {
                   Gson gson = new Gson();
                    //获取返回的原始json字符串
                    User user = response.body().getData();
                    Log.d(TAG, "获取的原始json字符串: " + user.toString());
                  Type myType = new TypeToken<ServerResponse<User>>() {
                    }.getType();

                  ServerResponse<User> response1 = gson.fromJson(user.toString(), myType);
                    if (response1 != null) {
                        Toast.makeText(Login.this, "登陆成功" + response1.getMsg(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(Login.this, "解析出了问题", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onFailure(Call<ServerResponse<User>> call, Throwable t) {
                    Log.d(TAG, "onFailure: ");
                    toastShort("登陆失败！");
                         });
            }*/


    /* //获取产品列表，对应第三个button
     public void getProductList(View view) {

         Retrofit retrofit = new Retrofit.Builder()
                 .baseUrl(RequestInterface.basePath)
                 .addConverterFactory(GsonConverterFactory.create())
                 .build();

         RequestInterface.getProductsList2 getProductsList = retrofit.create(RequestInterface.getProductsList2.class);

         Call<ServerResponse<MyPageInfo<Product>>> call = getProductsList.getProducts("电", 100001, 1, 8, "");

         call.enqueue(new Callback<ServerResponse<MyPageInfo<Product>>>() {

             @Override
             public void onResponse(Call<ServerResponse<MyPageInfo<Product>>> call, Response<ServerResponse<MyPageInfo<Product>>> response) {
 //                Log.d(TAG, "onResponse: " + response.body().getData());
                 //获取返回的数据（就是ServerResponse<T>中的T代表的东西）
                 MyPageInfo<Product> pageInfo = response.body().getData();
                 //在PageInfo中通过list获取到产品的集合（多个product对象）
                 List<Product> productList = pageInfo.getList();
                 //循环遍历，通过log输出产品信息
                 for (Product product : productList) {
                     Log.d(TAG, "onResponse: ####product#######" + product.toString());
                 }
             }

             @Override
             public void onFailure(Call<ServerResponse<MyPageInfo<Product>>> call, Throwable t) {
                 Log.d(TAG, "onFailure: ");
                 Toast.makeText(LoginActivity.this, "网络请求错误" + t.getMessage(), Toast.LENGTH_LONG).show();
             }
         });
     }
 */
}

